import React, { Component } from "react";
import "./Website.css";
import axios from "../../utils/http";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default class Website extends Component {
    state = {
        title: "",
        url: "",
        keywords: "",
        gjz: "",
        //状态  列表渲染的数据 初始值一定要给数组
        data: [],
        //双击更新的状态
        isDBClick: false, //是否双击
        dbID: null, //双击的 id 值
    };

    render() {
        return (
            <div className="website-container">
                <ToastContainer />
                <h2>网址管理</h2>
                <hr />
                <div className="form">
                    名称:{" "}
                    <input
                        type="text"
                        value={this.state.title}
                        name="title"
                        onChange={this.saveData}
                    />
                    &nbsp;&nbsp; 网址:{" "}
                    <input
                        type="text"
                        value={this.state.url}
                        name="url"
                        onChange={this.saveData}
                    />
                    &nbsp;&nbsp; 关键字:{" "}
                    <input
                        type="text"
                        value={this.state.keywords}
                        name="keywords"
                        onChange={this.saveData}
                    />
                    &nbsp;&nbsp;
                    <button onClick={this.add}>新增</button>
                </div>
                <hr />
                <div className="search">
                    <input
                        type="text"
                        value={this.state.gjz}
                        name="gjz"
                        onChange={this.saveData}
                    />{" "}
                    &nbsp;
                    <button onClick={this.search}>搜索</button>
                </div>
                <hr />
                <table border="1">
                    <thead>
                        <tr>
                            <td>ID</td>
                            <td>网站名称</td>
                            <td>网址</td>
                            <td>关键字</td>
                            <td>操作</td>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.data.map((item) => {
                            return (
                                <tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>{item.title}</td>
                                    <td
                                        onDoubleClick={this.handleDblclick(
                                            item.id
                                        )}
                                    >
                                        {/* 如果已经双击, 并且双击的 id 与当前 tr 的 id 是一致的, 则渲染 input 组件 */}
                                        {this.state.isDBClick &&
                                        this.state.dbID === item.id ? (
                                            <input
                                                onBlur={this.update(item.id)}
                                                autoFocus
                                                type="text"
                                                defaultValue={item.url}
                                            />
                                        ) : (
                                            item.url
                                        )}
                                    </td>
                                    <td>{item.keywords}</td>
                                    <td>
                                        <button onClick={this.remove(item.id)}>
                                            删除
                                        </button>
                                    </td>
                                </tr>
                            );
                        })}
                        {this.state.data.length === 0 && (
                            <tr>
                                <td colSpan="5" style={{ textAlign: "center" }}>
                                    暂无数据
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        );
    }

    //更新网址
    update = (id) => {
        // 发送请求  patch  /website/1
        // id  新网址
        return async (e) => {
            //发送请求
            await axios.patch("/website/" + id, { url: e.target.value });
            //成功的情况
            //提示
            toast.success("更新成功", {
                position: toast.POSITION.TOP_CENTER,
            });
            //更新数组数据
            let { data } = this.state;
            let newData = data.map((item) => {
                if (item.id === id) {
                    //修改该网址的 url
                    item.url = e.target.value;
                }
                //返回 item
                return item;
            });
            //修改状态
            this.setState({
                isDBClick: false,
                data: newData,
            });
        };
    };

    //双击的回调
    handleDblclick = (id) => {
        return () => {
            //修改是否双击的状态
            this.setState({
                isDBClick: true,
                dbID: id,
            });
        };
    };

    //搜索功能  http://localhost:3001/website?q=学习
    search = async () => {
        //获取关键字输入的内容
        let { gjz } = this.state;
        // 发送请求
        let result = await axios("/website", {
            params: {
                q: gjz,
            },
        });
        //更新列表
        let newData = result;
        this.setState({
            data: newData,
        });
    };

    //删除某个网址
    remove = (id) => {
        // delete   /website/10
        return async () => {
            //确认框的提示
            if (!window.confirm("您确定要删除当前的网址么??")) return;
            //发送请求
            await axios({
                method: "delete",
                url: "/website/" + id,
            });
            //提示
            toast.success("删除成功", {
                position: toast.POSITION.TOP_CENTER,
            });
            //更新列表
            let newData = this.state.data.filter((item) => item.id !== id);
            //设置状态
            this.setState({
                data: newData,
            });
        };
    };

    //保存表单数据
    saveData = (e) => {
        //修改状态
        this.setState({
            [e.target.name]: e.target.value,
        });
    };

    //新增网址
    add = async () => {
        //获取三个表单元素的输入值
        let { title, url, keywords } = this.state;
        //发送 AJAX     {title, url, keywords}
        //1. 准备数据
        let obj = {
            title,
            url,
            keywords,
        };
        //2. 发送 AJAX 请求
        let result = await axios.post("/website", obj);
        //清空表单  <input value={this.state.title} />
        this.setState({
            title: "",
            url: "",
            keywords: "",
        });
        //提示
        toast.success("添加成功", {
            position: toast.POSITION.TOP_CENTER,
            autoClose: 1500,
            closeOnClick: true,
            pauseOnFocusLoss: false,
        });
        //手动调用 componentDidMount  效率较低
        //直接更新 state 中 data 的值
        let { data } = this.state;
        //将服务器返回的数据对象, 压入到 data 数组中
        let newData = [...data, result];
        //更新状态
        this.setState({
            data: newData,
        });
    };

    //生命周期钩子
    async componentDidMount() {
        //发送请求
        let result = await axios("/website");
        //更新组件
        this.setState({
            data: result,
        });
    }
}


